﻿using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Media;

using Microsoft.Win32;

namespace PracticalProjects
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private enum DWMAttribute
        {
            DWMNCRENDERING_ENABLED = 1,
            DWMCAPTIONBUTTONS = 2, // 控制标题栏按钮的显示
            // 其他 DWM 属性...
        }

        // 调用系统API
        [DllImport("dwmapi.dll", EntryPoint = "DwmGetColorizationColor")]
        public static extern int DwmGetColorizationColor(out uint color, out bool opaque);

        [DllImport("dwmapi.dll", CallingConvention = CallingConvention.StdCall)]
        private static extern int DwmSetWindowAttribute(IntPtr hwnd, DWMAttribute attribute, int value);

        [DllImport("dwmapi.dll", PreserveSig = false)]
        private static extern void DwmSetWindowAttribute(IntPtr hwnd, int attr, ref int attrValue, int attrSize);

        [DllImport("dwmapi.dll", CallingConvention = CallingConvention.StdCall)]
        private static extern int DwmSetColorizationColor(uint colorizationColor, bool opaque);

        public void SetWindowBackgroundToTitleBarColor()
        {
            int result = DwmGetColorizationColor(out uint color, out bool opaque);
            if (result == 0)
            {
                // 提取ARGB颜色值
                byte a = (byte)((color >> 24) & 0xff);
                byte r = (byte)((color >> 16) & 0xff);
                byte g = (byte)((color >> 8) & 0xff);
                byte b = (byte)(color & 0xff);

                // 设置窗口背景色
                this.Background = new SolidColorBrush(Color.FromArgb(a, r, g, b));
                // this.Background = new SolidColorBrush(Color.FromArgb(255,240, 244, 249));

                this.Title = "[YES]已获取标题栏颜色";
            }
            else
            {
                this.Title = "[NO]未获取标题栏颜色";
            }
        }

        private void SetTitleBarColor()
        {
            // 设置标题栏颜色
            Color color = Color.FromArgb(255, 240, 244, 249); // 你想要的颜色
            var accentColor = (uint)((color.A << 24) | (color.R << 16) | (color.G << 8) | color.B);

            // 设置窗口句柄
            var windowHelper = new WindowInteropHelper(this);
            IntPtr hwnd = windowHelper.Handle;

            // 设置 DWM 属性
            int result = DwmSetWindowAttribute(hwnd, DWMAttribute.DWMNCRENDERING_ENABLED, 1);
            if (result < 0)
            {
                // 处理错误
                Debug.WriteLine("[1]处理错误");
            }

            result = DwmSetColorizationColor(accentColor, true);
            if (result < 0)
            {
                // 处理错误
                Debug.WriteLine("[2]处理错误");
            }
        }

        // 导入方法和结构体定义
        [DllImport("user32.dll")]
        private static extern int SetWindowCompositionAttribute(IntPtr hwnd, ref WindowCompositionAttributeData data);

        private enum WindowCompositionAttribute
        {
            WCA_ACCENT_POLICY = 19
        }

        private struct AccentPolicy
        {
            public AccentState AccentState;
            public int AccentFlags;
            public int GradientColor;
            public int AnimationId;
        }

        private enum AccentState
        {
            ACCENT_DISABLED = 0,
            ACCENT_ENABLE_GRADIENT = 1,
            ACCENT_ENABLE_TRANSPARENTGRADIENT = 2,
            ACCENT_ENABLE_BLURBEHIND = 3,
            ACCENT_ENABLE_ACRYLICBLURBEHIND = 4, // 适用于 Windows 10 的亚克力效果
            ACCENT_ENABLE_HOSTBACKDROP = 5      // 适用于 Windows 11 的云母效果
        }

        private struct WindowCompositionAttributeData
        {
            public WindowCompositionAttribute Attribute;
            public IntPtr Data;
            public int SizeOfData;
        }

        private void EnableMicaEffect()
        {
            var windowHelper = new WindowInteropHelper(this);
            var hwnd = windowHelper.Handle;

            var attribute = new WindowCompositionAttributeData();
            attribute.Attribute = WindowCompositionAttribute.WCA_ACCENT_POLICY;

            var accent = new AccentPolicy();
            accent.AccentState = AccentState.ACCENT_ENABLE_ACRYLICBLURBEHIND; // 亚克力模糊效果
            accent.GradientColor = unchecked((int)0x99000000); // 设置透明度

            int accentStructSize = Marshal.SizeOf(accent);
            IntPtr accentPtr = Marshal.AllocHGlobal(accentStructSize);
            Marshal.StructureToPtr(accent, accentPtr, false);

            attribute.SizeOfData = accentStructSize;
            attribute.Data = accentPtr;

            SetWindowCompositionAttribute(hwnd, ref attribute);
            Marshal.FreeHGlobal(accentPtr);
        }

        public MainWindow()
        {
            InitializeComponent();
            // SetTitleBarColor();
            // SetWindowBackgroundToTitleBarColor();
            // EnableMicaEffect();

            this.Loaded += MainWindow_Loaded;
        }

        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            // var hwnd = new WindowInteropHelper(this).Handle;
            // Color colorToSet = Color.FromArgb(255, 240, 244, 249);
            // int argbValue = (colorToSet.A << 24) | (colorToSet.R << 16) | (colorToSet.G << 8) | colorToSet.R;
            // int colorValue = argbValue & 0x00FFFFFF;
            // DwmSetWindowAttribute(hwnd, 35, ref colorValue, sizeof(int));

            // string osVersion = Environment.OSVersion.VersionString;

            using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion"))
            {
                string productName = key.GetValue("ProductName") as string;
                int majorVersion = (int)key.GetValue("CurrentMajorVersionNumber");
                var buildNumber = int.Parse(key.GetValue("CurrentBuildNumber").ToString());

                Debug.WriteLine(productName);
                Debug.WriteLine(majorVersion);
                Debug.WriteLine(buildNumber);

                if (!string.IsNullOrEmpty(productName) && productName.ToLower().Contains("windows"))
                {
                    if (majorVersion > 10 || majorVersion == 10 && buildNumber >= 22000)
                    {
                        // 当前系统是Windows 11
                        this.Background = new SolidColorBrush(Color.FromArgb(255, 240, 244, 249));
                    }
                    else if (majorVersion == 10 && buildNumber < 22000)
                    {
                        // 当前系统是Windows 10
                        this.Background = new SolidColorBrush(Colors.White);
                    }
                    else
                    {
                        // 当前系统不是Windows 10也不是Windows 11
                        this.Background = new SolidColorBrush(Colors.White);
                        // this.Background = new SolidColorBrush(Color.FromArgb(255, 240, 244, 249));
                    }
                }
                // string str = "环境设置";
                // Debug.WriteLine(ToTraditional(str, LCMAP_TRADITIONAL_CHINESE));
            }

            // SetWindowBackgroundToTitleBarColor();
            // EnableMicaEffect();
        }
    }
}
